package com.example.yichuangyun.ui.adapter;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.example.yichuangyun.R;
import com.example.yichuangyun.config.Constant;
import com.example.yichuangyun.databinding.ItemMyBusinessBinding;
import com.example.yichuangyun.databinding.LayoutEmptyListBinding;
import com.example.yichuangyun.model.business.BusinessModel;
import com.example.yichuangyun.model.business.ProductModel;
import com.example.yichuangyun.model.business.TelModel;
import com.example.yichuangyun.mvvm.ui.activity.CompanyDetailsActivity;
import com.example.yichuangyun.ui.activity.business.BusinessDetailsActivity;
import com.example.yichuangyun.ui.activity.follow.AddFollowActivity;
import com.example.yichuangyun.utils.CommonUtil;
import com.example.yichuangyun.utils.JumpIntent;
import com.example.yichuangyun.utils.ToastHelper;
import com.example.yichuangyun.utils.UMengUtil;

import java.util.ArrayList;
import java.util.List;

public class BusinessAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

    private int businessType = 2;
    /**
     * viewType--分别为item以及空view
     */
    private final int VIEW_TYPE_ITEM = 1;
    private static final int VIEW_TYPE_EMPTY = 0;
    private final Context context;
    private List<BusinessModel> mData;
    private OnCallListener onCallListener;
    private OnMoreListener onMoreListener;

    public BusinessAdapter(Context context, List<BusinessModel> mData) {
        this.context = context;
        this.mData = mData;
    }

    public void onRefresh(List<BusinessModel> mList) {
        if (mList != null) {
            if (mData == null) {
                mData = new ArrayList<>();
            }
            this.mData.clear();
            this.mData.addAll(mList);
            notifyDataSetChanged();
        }
    }

    public void addData(List<BusinessModel> mList) {
        if (mList != null && mList.size() != 0) {
            if (mData == null) {
                mData = new ArrayList<>();
            }
            this.mData.addAll(mList);
            notifyDataSetChanged();
        }
    }

    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        //在这里根据不同的viewType进行引入不同的布局
        if (viewType == VIEW_TYPE_EMPTY) {
            LayoutEmptyListBinding emptyListBinding = LayoutEmptyListBinding.inflate(LayoutInflater.from(context), parent, false);
            return new EmptyViewHolder(emptyListBinding);
        } else {
            ItemMyBusinessBinding itemMyBusinessBinding = ItemMyBusinessBinding.inflate(LayoutInflater.from(context), parent, false);
            return new MyViewHolder(itemMyBusinessBinding);
        }
    }

    @SuppressLint("SetTextI18n")
    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
        if (holder instanceof MyViewHolder) {
            BusinessModel model = mData.get(position);
            MyViewHolder myViewHolder = (MyViewHolder) holder;
            if (businessType == 10) { // 全部商机里不显示待废弃和待审核
                myViewHolder.binding.tvName.setTextColor(context.getColor(R.color.color_4A4A4A));
                myViewHolder.binding.tvPhone.setTextColor(context.getColor(R.color.color_4A4A4A));
                myViewHolder.binding.tvDiscardStatus.setText("");
                myViewHolder.binding.tvDiscardStatus.setVisibility(View.INVISIBLE);
            } else {
                if (businessType == 0 || businessType == 1) {
                    myViewHolder.binding.tvName.setTextColor(context.getColor(model.getDiscardStatus() == 1 || model.getDiscardStatus() == 3 ? R.color.color_F97A7A : R.color.color_4A4A4A));
                    myViewHolder.binding.tvPhone.setTextColor(context.getColor(model.getDiscardStatus() == 1 || model.getDiscardStatus() == 3 ? R.color.color_F97A7A : R.color.color_4A4A4A));
                    myViewHolder.binding.tvDiscardStatus.setText(model.getDiscardStatus() == 1 ? context.getString(R.string.wait_discard) : model.getDiscardStatus() == 3 ? context.getString(R.string.wait_discard_again) : "");
                    myViewHolder.binding.tvDiscardStatus.setVisibility(model.getDiscardStatus() == 1 || model.getDiscardStatus() == 3 ? View.VISIBLE : View.INVISIBLE);
                } else { // 我跟进和部门跟进的商机显示待废弃，不显示待复核
                    myViewHolder.binding.tvName.setTextColor(context.getColor(model.getDiscardStatus() == 1 ? R.color.color_F97A7A : R.color.color_4A4A4A));
                    myViewHolder.binding.tvPhone.setTextColor(context.getColor(model.getDiscardStatus() == 1 ? R.color.color_F97A7A : R.color.color_4A4A4A));
                    myViewHolder.binding.tvDiscardStatus.setText(model.getDiscardStatus() == 1 ? context.getString(R.string.wait_discard) : "");
                    myViewHolder.binding.tvDiscardStatus.setVisibility(model.getDiscardStatus() == 1 ? View.VISIBLE : View.INVISIBLE);
                }
            }

            if (model.getUsers() != null && model.getUsers().size() > 0) {
                boolean isHasDefault = false;
                for (TelModel telModel : model.getUsers()) {
                    if (telModel.getIsDefault() == 1) {
                        isHasDefault = true;
                        myViewHolder.binding.tvName.setText(telModel.getUsername());
                        if (!TextUtils.isEmpty(telModel.getTelNumber().get(0)) && telModel.getTelNumber().get(0).length() > 4) {
                            myViewHolder.binding.tvPhone.setText("·" + CommonUtil.getStarPhone(telModel.getTelNumber().get(0)));
                        }
                        break;
                    }
                }
                if (!isHasDefault) {
                    myViewHolder.binding.tvName.setText(model.getUsers().get(0).getUsername());
                }
            }
            StringBuilder builder = new StringBuilder();
            if (model.getProducts() != null && model.getProducts().size() > 0) {
                for (int i = 0; i < model.getProducts().size(); i++) {
                    ProductModel productModel = model.getProducts().get(i);
                    String pName = TextUtils.isEmpty(productModel.getProductFullName()) ? productModel.getProductName() : productModel.getProductFullName();
                    if (model.getProducts().size() > 3 && i == 2) {
                        builder.append(pName).append("...");
                        break;
                    } else if (i == model.getProducts().size() - 1) {
                        builder.append(pName);
                    } else {
                        builder.append(pName).append("\n");
                    }
                }
            }
            myViewHolder.binding.tvProductName.setText(builder.toString());
            myViewHolder.binding.tvOldCustomer.setVisibility(model.getOldUser() == 1 ? View.VISIBLE : View.GONE);
            if (!TextUtils.isEmpty(model.getCompName())) {
                myViewHolder.binding.tvCompanyName.setText(model.getCompName().contains("系统生成企业") ? "/" : model.getCompName());
            } else {
                myViewHolder.binding.tvCompanyName.setText("/");
            }
            myViewHolder.binding.tvStatus.setText(CommonUtil.checkText(model.getStepStatusName()));
            myViewHolder.binding.tvCreatePerson.setText(CommonUtil.checkText(model.getCreateUser()));
            myViewHolder.binding.tvFollowPerson.setText(TextUtils.isEmpty(model.getGdUser()) ? context.getString(R.string.no) : model.getGdUser());
            myViewHolder.binding.tvCreateTime.setText(String.format(context.getString(R.string.create_time_mao), CommonUtil.checkText(model.getCreateTime())));
            myViewHolder.binding.tvNextFollowTime.setText(String.format(context.getString(R.string.next_follow_time3), CommonUtil.setYHMTime(model.getNextFollowTime())));
            myViewHolder.binding.tvIntoTime.setText(String.format(context.getString(R.string.into_time), CommonUtil.setText(model.getIntoChanceTime())));
            if (model.getLostRemindHour() != null) {
                myViewHolder.binding.tvLostOrderTips.setVisibility(View.VISIBLE);
                myViewHolder.binding.tvLostOrderTips.setText(String.format(context.getString(R.string.lost_order_tips), model.getLostRemindHour()));
            } else {
                myViewHolder.binding.tvLostOrderTips.setVisibility(View.GONE);
            }
            int stepStatus = model.getStepStatus();
            myViewHolder.binding.tvFollowText.setTextColor(stepStatus == 60 || stepStatus == 80 || model.getDiscardStatus() != 0 ? 0xFF7C7C7C : 0xFF426FFF);
            myViewHolder.binding.llAddFollow.setOnClickListener(v -> {
                UMengUtil.setCountEventId(Constant.LIST_ADD_FOLLOW);
                if (stepStatus == 60 || stepStatus == 80 || model.getDiscardStatus() != 0) {
                    Bundle bundle = new Bundle();
                    bundle.putInt(Constant.businessTypeKey, businessType);
//                    bundle.putSerializable(Constant.modelKey, model);
                    bundle.putParcelable(Constant.modelKey, model);
                    JumpIntent.jump((Activity) context, BusinessDetailsActivity.class, bundle);
                } else {
                    ArrayList<String> mTelList = new ArrayList<>();
                    String userName = null;
                    for (TelModel telModel : model.getUsers()) {
                        userName = telModel.getUsername();
                        mTelList.addAll(telModel.getTelNumber());
                    }
                    Bundle bundle = new Bundle();
                    bundle.putInt(Constant.flagKey, 0);
                    bundle.putString(Constant.businessIdKey, model.getId());
                    bundle.putString(Constant.nameKey, userName);
                    bundle.putStringArrayList(Constant.telKey, mTelList);
                    JumpIntent.jump((Activity) context, AddFollowActivity.class, bundle);
                }
            });

            myViewHolder.binding.llCall.setOnClickListener(v -> {
                if (CommonUtil.isCanClick()) {
                    UMengUtil.setCountEventId(Constant.LIST_CALL);
                    if (onCallListener != null) {
                        List<String> mTelList = new ArrayList<>();
                        if (model.getUsers() != null && model.getUsers().size() > 0) {
                            for (TelModel telModel : model.getUsers()) {
                                mTelList.addAll(telModel.getTelNumber());
                            }
                            onCallListener.callListener(mTelList, model.getId(), model.getUserName());
                        } else {
                            ToastHelper.show(context.getString(R.string.no_contact_phone));
                        }
                    } else {
                        ToastHelper.show(context.getString(R.string.no_contact_phone));
                    }
                }
            });

            // 废弃状态：0未废弃，1废弃审核中 2已废弃 3待复核
            if (model.getDiscardStatus() == 0) {
                myViewHolder.binding.tvMoreText.setTextColor(stepStatus == 60 || stepStatus == 70 || stepStatus == 80 ? 0xFF7C7C7C : 0xFF426FFF);
            } else if (model.getDiscardStatus() == 1) {
                myViewHolder.binding.tvMoreText.setTextColor(businessType == 0 || businessType == 1 ? 0xFF426FFF : 0xFF7C7C7C);
            } else {
                myViewHolder.binding.tvMoreText.setTextColor(0xFF7C7C7C);
            }

            myViewHolder.binding.llMore.setOnClickListener(v -> {
                if (CommonUtil.isCanClick() && onMoreListener != null) {
                    List<String> titleData = new ArrayList<>();
                    if (model.getDiscardStatus() == 0) {
                        if (stepStatus == 60 || stepStatus == 70 || stepStatus == 80) {
                            Bundle bundle = new Bundle();
                            bundle.putInt(Constant.businessTypeKey, businessType);
//                            bundle.putSerializable(Constant.modelKey, model);
                            bundle.putParcelable(Constant.modelKey, model);
                            JumpIntent.jump((Activity) context, BusinessDetailsActivity.class, bundle);
                        } else {
                            // 已生成订单、商机进展为废弃（包含废弃审核中）、签约成功的商机、商机跟进人为公海或商机池的商机，没有“生成订单”按钮；共享给我的，共享给部门的， 都不能生成订单，以及丢单和废弃
                            // 0-我创建的、1-部门创建的、 2-我跟进的、 3-部门跟进的、4-共享给我的、5-共享给部门的
                            if (!model.getGdUser().equals(context.getString(R.string.gh)) && !model.getGdUser().equals(context.getString(R.string.business_pool)) && model.getIsOrder() != 1 && businessType != 4 && businessType != 5) {
                                if (businessType == 0 || businessType == 1) { // 我创建的/部门创建的页面，创建人和跟进人不是同一个人的话，创建人不能生成订单，丢单或者废弃的
                                    if (model.getCreateUserId().equals(model.getGdUserId())) {
                                        titleData.add(context.getString(R.string.create_order));
                                    }
                                } else {
                                    titleData.add(context.getString(R.string.create_order));
                                }
                            }
                            // businessStepStatus：10新入库 20需跟踪 30确认意向 40邀约成功 50面谈成功 60签约成功 70丢单 80废弃 90未签约
                            // 新入库、需跟踪、确认意向、邀约成功、面谈成功、未签约 --> 拨打电话、跟进、编辑、废弃/丢单（老客户的商机才可以废弃），设置共享人；
                            titleData.add(context.getString(R.string.set_share_person));
                            // 商机跟进人为公海或商机池的商机，没有废弃或丢单按钮；共享给我的，共享给部门的， 都不能生成订单，以及丢单和废弃
                            if (!model.getGdUser().equals(context.getString(R.string.gh)) && !model.getGdUser().equals(context.getString(R.string.business_pool)) && businessType != 4 && businessType != 5) {
                                if (businessType == 0 || businessType == 1) { // 我创建的/部门创建的页面，创建人和跟进人不是同一个人的话，创建人不能生成订单，丢单或者废弃的
                                    if (model.getCreateUserId().equals(model.getGdUserId())) {
                                        titleData.add(model.getOldUser() == 1 ? context.getString(R.string.discard) : context.getString(R.string.lost_order));
                                    }
                                } else {
                                    titleData.add(model.getOldUser() == 1 ? context.getString(R.string.discard) : context.getString(R.string.lost_order));
                                }
                            }
                            onMoreListener.moreListener(model, titleData);
                        }
                    } else if (model.getDiscardStatus() == 1) {
                        if (businessType == 0 || businessType == 1) {
                            titleData.add(context.getString(R.string.discard_examine));
                            onMoreListener.moreListener(model, titleData);
                        }
                    } else {
                        Bundle bundle = new Bundle();
                        bundle.putInt(Constant.businessTypeKey, businessType);
                        bundle.putParcelable(Constant.modelKey, model);
                        JumpIntent.jump((Activity) context, BusinessDetailsActivity.class, bundle);
                    }
                }
            });

            myViewHolder.binding.tvCompanyName.setOnClickListener(view -> {
                if (CommonUtil.isCanClick()) {
                    Bundle bundle = new Bundle();
                    bundle.putString(Constant.creditNoKey, model.getCreditNo());
                    JumpIntent.jump((Activity) context, CompanyDetailsActivity.class, bundle);
                }
            });

            myViewHolder.itemView.setOnClickListener(v -> {
                Bundle bundle = new Bundle();
                bundle.putInt(Constant.businessTypeKey, businessType);
                bundle.putParcelable(Constant.modelKey, model);
                JumpIntent.jump((Activity) context, BusinessDetailsActivity.class, bundle);
            });
        } else if (holder instanceof EmptyViewHolder) {
            EmptyViewHolder emptyHolder = (EmptyViewHolder) holder;
            emptyHolder.binding.text.setText(context.getString(R.string.no_business));
        }
    }

    @Override
    public int getItemCount() {
        //同时这里也需要添加判断，如果mData.size()为0的话，只引入一个布局，就是emptyView
        // 那么，这个recyclerView的itemCount为1
        if (mData.size() == 0) {
            return 1;
        }
        //如果不为0，按正常的流程跑
        return mData.size();
    }

    @Override
    public int getItemViewType(int position) {
        //在这里进行判断，如果我们的集合的长度为0时，我们就使用emptyView的布局
        if (mData.size() == 0) {
            return VIEW_TYPE_EMPTY;
        }
        //如果有数据，则使用ITEM的布局
        return VIEW_TYPE_ITEM;
    }

    public void setBusinessType(int businessType) {
        this.businessType = businessType;
    }

    static class MyViewHolder extends RecyclerView.ViewHolder {

        ItemMyBusinessBinding binding;

        public MyViewHolder(ItemMyBusinessBinding itemMyBusinessBinding) {
            super(itemMyBusinessBinding.getRoot());
            binding = itemMyBusinessBinding;
        }
    }

    static class EmptyViewHolder extends RecyclerView.ViewHolder {

        LayoutEmptyListBinding binding;

        public EmptyViewHolder(LayoutEmptyListBinding emptyListBinding) {
            super(emptyListBinding.getRoot());
            binding = emptyListBinding;
        }
    }

    public interface OnCallListener {
        void callListener(List<String> telList, String id, String userName);
    }

    public void setOnCallListener(OnCallListener onCallListener) {
        this.onCallListener = onCallListener;
    }

    public interface OnMoreListener {
        void moreListener(BusinessModel businessModel, List<String> titleData);
    }

    public void setOnMoreListener(OnMoreListener onMoreListener) {
        this.onMoreListener = onMoreListener;
    }
}
